package admin

import (
	"context"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/admin/adminLogic"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/admin/roleLogic"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
)

func (rpc *admin) AdminRoleMulti(ctx context.Context, pb *pbAdmin.AdminRoleMultiReq) (*pbAdmin.AdminRoleMultiResp, error) {
	// 可以修改的字段
	multiFields := map[string]string{
		"status": "status",
	}

	if _, ok := multiFields[pb.Field]; !ok {
		return nil, businessError.ErrorInfoToRpcError(businessError.OperateFieldError)
	}

	ids := []interface{}{}
	for _, id := range pb.Id {
		ids = append(ids, id)
	}

	if pb.OperaterId != 0 {
		roleIds := adminLogic.GetChildrenRoleIds(ctx, pb.OperaterId, true)
		if len(utils.ArrayDiff(ids, roleIds)) > 0 {
			return nil, businessError.ErrorInfoToRpcError(businessError.AdminDeniedOperateSelfRole)
		}
	}

	Db := database.Db.GetDefaultDb(ctx)

	if values, ok := roleLogic.List()[pb.Field]; ok {
		if _, ok = values[pb.Value]; !ok {
			return nil, businessError.ErrorInfoToRpcError(businessError.OperateValueError)
		}
	}

	rowCount, dbErr := Db.Update("admin_role", map[string]interface{}{
		pb.Field: pb.Value,
	}, map[string]interface{}{
		"id": ids,
	})

	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	return &pbAdmin.AdminRoleMultiResp{
		RowCount: rowCount,
	}, nil
}
